package com.itheima.security;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class SpringSecurityDemo implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1 根据username从数据库查询，获得User对象
        User user = findByUserName(username);
        //2 校验user是否为空
        if (null == user) {
            return null;
        }
        //3 数据库中的用户名、密码、权限、角色存到UserDetails对象中并返回
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        list.add(new SimpleGrantedAuthority("ROLE_add"));
        list.add(new SimpleGrantedAuthority("update"));
        list.add(new SimpleGrantedAuthority("delete"));
//        list.add(new SimpleGrantedAuthority("find"));
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        list.add(new SimpleGrantedAuthority("ROLE_EDIT"));

        org.springframework.security.core.userdetails.User userDetail =
                new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
        return userDetail;
    }

    private User findByUserName(String username) {
        if(!StringUtils.isEquals(username,"admin")){
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(encoder.encode("12345678"));
        return user;
    }


}
